﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TimeToGo.Configuration;
using System.Configuration;

namespace TimeToGo.Repositories
{
    internal class TimeInfoRepository : IRepository<TimeInfo>
    {

        public TimeInfo Add(TimeInfo entity)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            TimeInfoConfigurationSection section = (TimeInfoConfigurationSection)config.Sections[ConfigurationConstants.TimeConfiguration];

            section.TimeInfos.Add(new TimeInfoConfigurationElement { Name = entity.Name, Time = entity.Time });
            config.Save();
            return entity;
        }

        public void Remove(TimeInfo entity)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            TimeInfoConfigurationSection section = (TimeInfoConfigurationSection)config.Sections[ConfigurationConstants.TimeConfiguration];

            section.TimeInfos.Remove(entity.Name);
            config.Save();
        }

        public void Modify(TimeInfo entity)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            TimeInfoConfigurationSection section = (TimeInfoConfigurationSection)config.Sections[ConfigurationConstants.TimeConfiguration];

            foreach (TimeInfoConfigurationElement te in section.TimeInfos)
            {
                if (te.Name == entity.Name)
                {
                    te.Time = entity.Time;
                }
            }
            
            config.Save();
        }

        public IEnumerable<TimeInfo> FindAll()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            TimeInfoConfigurationSection section = (TimeInfoConfigurationSection)config.Sections[ConfigurationConstants.TimeConfiguration];
            List<TimeInfo> list = new List<TimeInfo>();

            foreach (TimeInfoConfigurationElement te in section.TimeInfos)
                list.Add(new TimeInfo { Name = te.Name, Time = te.Time });
            
            return list;
        }
    }
}
